package com.leff.cards.ui.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar.Tab;

public class FragmentTabListener<T extends Fragment> implements com.actionbarsherlock.app.ActionBar.TabListener  {

	private Fragment mFragment;
	private final FragmentActivity mHost;
	private final String mTag;
	private final Class<T> mClass;
	private int mContainerId;
	
	public FragmentTabListener(FragmentActivity host, String tag, Class<T> clazz) {
		this(host, tag, clazz, android.R.id.content);
	}
	public FragmentTabListener(FragmentActivity host, String tag, Class<T> clazz, int containerId) {
		
		mHost = host;
		mTag = tag;
		mClass = clazz;
		mContainerId = containerId;
		
		mFragment = mHost.getSupportFragmentManager().findFragmentByTag(mTag);
        if (mFragment != null && !mFragment.isDetached()) {
            FragmentTransaction ft = mHost.getSupportFragmentManager().beginTransaction();
            ft.detach(mFragment);
            ft.commit();
        }
	}
	
	public void setContainerLayoutId(int id) {
		mContainerId = id;
	}
	
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		
		if(mFragment == null) {
			mFragment = Fragment.instantiate(mHost, mClass.getName());
			ft.add(mContainerId, mFragment, mTag);
		}
		else {
			ft.attach(mFragment);
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		if(mFragment != null) {
			ft.detach(mFragment);
		}
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
	}
}
